#include "DateBase.hpp"
#include <algorithm>

namespace MRMDS::Server
{
int DataBase::Login(std::string name, std::string password)
{
    if (std::count(passwords.begin(), passwords.end(), password))
    {
        id++;
        return id;
    }
    return -1;
}

bool DataBase::Logout(int id)
{
    if (instances.count(id))
    {
        instances.erase(id);
        return true;
    }
    return false;
}

std::map<int, std::string> DataBase::GetInstanceList(int filter)
{
    std::map<int, std::string> result;
    for (auto instancePair : instances)
    {
        if (instancePair.first & filter)
            result[instancePair.first] = instancePair.second.name;
    }
    return result;
}

std::map<int, std::map<int, std::variant<int, float, double, std::string>>> DataBase::GetValues(std::vector<int> &ids,
                                                                                                std::vector<int> &keys)
{
    std::lock_guard guard(instanceMtx);
    std::map<int, std::map<int, BasicValue>> result;
    for (int id : ids)
    {
        auto instance = instances.find(id);
        if (instance == instances.end())
        {
            continue;
        }
        std::map<int, BasicValue> instValueMap;
        for (int key : keys)
        {
            auto value = instance->second.values.find(key);
            if (value == instance->second.values.end())
            {
                continue;
            }
            instValueMap[key] = value->second;
        }
        result[id] = instValueMap;
    }
    return result;
}

bool DataBase::SetValue(int id, std::map<int, BasicValue> &values)
{
    std::lock_guard guard(instanceMtx);
    auto instance = instances.find(id);
    if (instance == instances.end())
    {
        return false;
    }
    for (auto keyPair : values)
    {
        auto value = instance->second.values.find(keyPair.first);
        if (value == instance->second.values.end())
        {
            continue;
        }
        instance->second.values[keyPair.first] = keyPair.second;
    }
    return true;
}
} // namespace MRMDS::Server